<script setup>
import { ref, computed, onMounted, onUpdated } from 'vue';
import { ElMessage } from 'element-plus';
import Bus from '../utils/bus.js';
import Cart from '../components/Cart.vue';


const isLogin = ref(false);
const avatarUrl = ref('./images/avatar.png');
const activeIndex = ref('1');
const productList = ref([
  { id: '1', type: '徽章', name: 'IT社区文创 ：「代码新秀闪耀」 荣誉徽章', price: 29, stock: 30, img: './images/product01.png' },
  { id: '2', type: '帆布包', name: '【it社区文创】「极简主义」帆布包', price: 79, stock: 60, img: './images/product02.png' },
  { id: '3', type: 'T恤', name: '蓝字魔法，解锁IT新风尚——百搭T恤衫', price: 12, stock: 100, img: './images/product03.png' },
  { id: '4', type: 'U盘', name: 'IT达人必备：128GB紫色技术社区U盘', price: 39, stock: 80, img: './images/product04.png' },
  { id: '5', type: '笔记本', name: '高端皮质IT笔记本，简约设计尽显专业气质', price: 29, stock: 30, img: './images/product05.png' },
]);

// const addToCart = (product) => {
//   emitter.emit('add-to-cart', product);
// };

const addToCart = (product) => {
  Bus.emit('add-to-cart', product)
  ElMessage.success(`${product.name} 已加入购物车`)
};

const goToLogin = () => {
  window.location.href = './login.html';
};

const goToProfile = () => {
  window.location.href = './person.html';
};

onMounted(() => {
  fetch('/api/products')
    .then(response => response.json())
    .then(data => {
      productList.value = data;
    })
    .catch(error => {
      ElMessage.error('加载商品失败：' + error.message);
    });
});
</script>

<template>
  <div>
    <el-container>
      <el-main>
        <el-row :gutter="20">
          <el-col 
            v-for="(product, i) in productList" 
            :key="i"
            :xs="24" 
            :sm="12" 
            :md="8"
          >
            <el-card class="product-card">
              <img :src="product.img" class="product-image" />
              <div class="product-info">
                <h4>{{ product.name }}</h4>
                <div class="meta-info">
                  <el-text type="primary" size="large">¥{{ product.price }}</el-text>
                  <el-text type="info">库存 {{ product.stock }}</el-text>
                </div>
                <el-button 
                  type="primary" 
                  @click="addToCart(product)"
                  class="add-btn"
                >
                  加入购物车
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
      
      <el-aside width="320px">
        <Cart />
      </el-aside>
    </el-container>
  </div>
</template>

<style scoped>
.product-card {
  margin-bottom: 20px;
}
.product-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  margin-bottom: 12px;
}
.product-info {
  padding: 0 12px;
}
.meta-info {
  margin: 12px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.add-btn {
  width: 100%;
}
</style>